/*
 * @author zhaozhenjiang
 * 备注：数据解密类
 * 版本:v1.0
 * */

package test.com;

import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;


final class desUtil {
	private static final String CIPHER_ALGORITHM_ECB = "DES/ECB/PKCS5Padding";
	private static final String KEY_ALGORITHM = "DES";
	private static desUtil du = null;
	private static final Object lock_du = new Object();
	
	private desUtil(){}
	
	public static desUtil getInstance(){
		if(du == null){
			synchronized (lock_du) {
				if(du == null)
					du = new desUtil();
			}
		}
		return du;
	}
	
    /**  
     * 还原密钥  
     *   
     * @param key  
     * @return  
     * @throws Exception   
     */    
    private static Key toKey(byte[] key) throws Exception {    
        DESKeySpec des = new DESKeySpec(key);    
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(KEY_ALGORITHM);    
        SecretKey secretKey = keyFactory.generateSecret(des);    
        return secretKey;    
    }
    
    /**  
     * 解密  
     * @param data 密文  
     * @param key  
     * @return 明文、原文  
     * @throws Exception  
     */    
    public byte[] decrypt(byte[] data, byte[] key) throws Exception {    
        Key k = toKey(key);
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM_ECB);    
        cipher.init(Cipher.DECRYPT_MODE, k);    
        return cipher.doFinal(data);
    }
    
    /**  
     * 加密   
     * @param data 原文  
     * @param key  
     * @return 密文  
     * @throws Exception  
     */    
    public byte[] encrypt(byte[] data, byte[] key) throws Exception {    
        Key k = toKey(key);
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM_ECB);    
        cipher.init(Cipher.ENCRYPT_MODE, k);
        return cipher.doFinal(data);    
    }
}
